<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/5
 * Time: 14:06
 */

namespace app\index\server;


use app\index\controller\WeChat;
use app\index\model\Agent as AgentModel;
use app\index\model\User as UserModel;
use app\lib\exception\DatabaseException;
use think\Controller;
use think\Exception;

class LoginRegServer extends Controller
{
    public function login($from)
    {
        if(!session('Auth.Openid')) {
            $we_chat = new WeChat();
            if($from == 'cart') {
                $wx_array = $we_chat->Authentication();
            } else {
                $wx_array = $we_chat->ToMyself();
            }
            $openid = $wx_array['openid'];
            session('Auth.Openid', $openid);
        } else {
            $openid = session('Auth.Openid');
        }
        // 数据库查找此信息
        $user_info = UserModel::where('openid', $openid)
            ->find();
        if(!$user_info) {
            // 没有此用户则去注册
            return $this->redirect('/reg');
        }
        session('Auth.Uid', $user_info->id);
        session('Auth.Username', $user_info->username);
        session('Auth.IsVIP', $user_info->is_vip);
        session('Auth.Openid', $openid);
        if($from == 'cart') {
            return $this->redirect('/cart');
        } else {
//            dump($from);die;
            return $this->redirect('/myself');
        }
    }

    public function reg($params = [])
    {
	$pid = $params['pid']?$params['pid'] : 0 ;
        // 邀请码
        if(!$params['code']) {
            $code_array = [
                'agent_id' => 1,
                'pAgent' => 0,
                'gAgent' => 0
            ];
        } else {
         //   $code_array = $this->code($params['code']) ?  $this->code($params['code']) : 0;
        }
        // 手机
        $mobile_result = $this->check_mobile($params['mobile']);
        if($mobile_result['status'] == 0) {
            return $mobile_result;
        }
        // 昵称
        $username_result = $this->check_name($params['username']);
        if($username_result['status'] == 0) {
            return $username_result;
        }
       // 数组
        $prep_data = [
            'mobile' => $params['mobile'],
            'username' => $params['username'],
            'surename' => $params['surename'],
	    'icon' => $params['icon'],
            'status' => 1,
            'agent_id' => $code_array['agent_id'],
            'p_id' => $pid,
            'g_id' => $code_array['gAgent'],
            'openid' => $params['openid']
        ];
        try {
//	$a == 0;
            $reg_result = UserModel::insertGetId($prep_data);
            if(!$reg_result) {
                return setMsg(0, '注册用户失败');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => $params['code'],
                'msg' => '注册用户时发生了错误',
                'msg' => $e->getMessage()
            ]);
        }
        session('Auth.Uid', $reg_result);
        session('Auth.Username', $prep_data['username']);
        session('Auth.Openid', $prep_data['openid']);
        session('Auth.IsVIP', 0);
        return setMsg(1, '注册用户成功');
    }

    // 检测用户名是否可用
    public function check_name($name)
    {
        try {
            $code = AgentModel::where('invitation_code', $name)
                ->find();
            $result = UserModel::where('username', $name)
                ->find();
            if($result || $code) {
                return [
                    'status' => 0,
                    'message' => '输入的用户名已注册'
                ];
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => 90002,
                'msg' => '非常抱歉,检测用户名时发生了错误,给您带来的不便请您谅解'
            ]);
        }
        return [
            'status' => 1,
            'message' => '输入的用户名可用'
        ];
    }

    // 检测电话号码是否可用
    public function check_mobile($mobile)
    {
        try {
            $result = UserModel::where('mobile', $mobile)
                ->find();
            if($result) {
                return [
                    'status' => 0,
                    'message' => '输入的手机号已注册'
                ];
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => 90002,
                'msg' => '非常抱歉,检测手机号时发生了错误,给您带来的不便请您谅解'
            ]);
        }
        return [
            'status' => 1,
            'message' => '输入的手机号可用'
        ];
    }

    // 检测邀请码
    public function code($code)
    {
        // 假设是用户的信息
        $user_info = UserModel::where('username', $code)
            ->find();
        if(!$user_info) {
            // 不是个人邀请码 是代理商邀请码
            $agent_info = AgentModel::where('invitation_code', $code)
                ->find();
            // 填错或者不填是自己商城的邀请
            if(!$agent_info) {
                return [
                    'agent_id' => 0,
                    'pAgent' => 0,
                    'gAgent' => 0
                ];
            }
            return [
                'agent_id' => $agent_info->id,
                'pAgent' => 0,
                'gAgent' => 0
            ];
        }
        return [
            'agent_id' => $user_info->agent_id,
            'pAgent' => $user_info->id,
            'gAgent' => $user_info->p_id
        ];
    }
}
